<template>
  <v-container class="questionnaire">
    <v-sheet
      class="my-4 pa-6 bg-grey-lighten-2"
      rounded
    >
      <v-row class="mb-2">
        <div class="mx-auto">
          {{ authStore.user?.username || "-" }} /
          {{ authStore.user?.sid || "-" }}
        </div>
        <div class="mx-auto">
          {{ authStore.user?.classname || "" }}
        </div>
        <div class="mx-auto">
          <a
            href=""
            @click="handleLogout"
          >
            登错账号? 重新登录
          </a>
        </div>
      </v-row>
      <v-row>
        <div class="mx-auto">
          <p class="text-h5 mb-4">{{ title }}</p>
        </div>
      </v-row>
      <v-row>
        <p class="mb-6">
          &nbsp;&nbsp;&nbsp;&nbsp;尊敬的用户，您好！为了更好地了解您的日常生活和学习情况，请您根据实际情况填写以下问卷。感谢您的配合！
        </p>
      </v-row>

      <v-form
        ref="formRef"
        v-model="formValue"
        v-if="questions.length > 0"
        @submit.prevent
      >
        <!-- 动态生成问卷问题 -->
        <div
          v-for="(question, index) in questions"
          :key="index"
          class="mb-4"
        >
          <p class="font-weight-bold">
            {{ index + 1 }}. {{ question.question_text }}
          </p>
          <v-row class="pa-0 ma-0">
            <v-col
              class="pa-0 ma-0"
              v-for="(option, optionIndex) in question.options"
              :key="optionIndex"
              cols="12"
            >
              <v-radio-group
                v-if="question.question_type === 'radio'"
                v-model="answers[`${question.qid}-${index}`]"
                hide-details="auto"
                :mandatory="true"
                :disabled="isAnswered"
                :rules="[required]"
                class="my-0"
              >
                <v-radio
                  :label="option"
                  :value="option"
                ></v-radio>
              </v-radio-group>
              <v-checkbox
                density="compact"
                hide-details="auto"
                v-else-if="question.question_type === 'checkbox'"
                v-model="answers[`${question.qid}-${index}`]"
                :disabled="isAnswered"
                multiple
                :rules="[required]"
                :label="option"
                :value="option"
                class="my-0"
              ></v-checkbox>
            </v-col>
          </v-row>
          <v-text-field
            density="compact"
            hide-details="auto"
            :disabled="isAnswered"
            :rules="[
              required,
              ...(question.question_text.includes('身高')
                ? [validateHeight]
                : []),
              ...(question.question_text.includes('体重')
                ? [validateWeight]
                : []),
            ]"
            v-if="question.question_type === 'text'"
            v-model="answers[`${question.qid}-${index}`]"
            variant="underlined"
          ></v-text-field>
        </div>
      </v-form>

      <!-- 加载状态 -->
      <v-alert
        v-else-if="loading"
        type="info"
        class="mt-6"
      >
        加载问卷中，请稍候...
      </v-alert>

      <!-- 错误状态 -->
      <v-alert
        v-else
        type="error"
        class="mt-6"
      >
        无法加载问卷内容，请稍后再试。
      </v-alert>
    </v-sheet>
    <!-- 提交按钮 -->
    <v-row
      v-if="!isAnswered"
      class="my-12 d-flex justify-center"
    >
      <v-btn
        type="submit"
        color="primary"
        @click="submitForm"
        :loading="isSubmitting"
      >
        提交问卷
      </v-btn>
    </v-row>
    <!-- 错误提示模态框 -->
    <v-dialog
      v-model="isModalOpen"
      :close-on-click="false"
      max-width="400px"
    >
      <v-card>
        <!-- 内容区域：显示消息详情 -->
        <v-card-text class="text-center py-4">
          <v-progress-circular
            indeterminate
            v-if="dialogType === 'info'"
          ></v-progress-circular>
          <v-alert
            v-else
            :type="dialogType"
            :dense="true"
            :icon="dialogIcon"
            class="w-full"
          >
            {{ dialogMessage }}
          </v-alert>
        </v-card-text>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup>
  import { ref, reactive } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import { getQuestionnaire, postAnswer } from "../api";
  import { useAuthStore } from "../stores/auth";

  const route = useRoute();
  const router = useRouter();
  const authStore = useAuthStore();

  const formRef = ref("");
  const formValue = ref("");
  // 模态框相关
  const isModalOpen = ref(false);
  const dialogType = ref("info"); // info, success, error
  const dialogIcon = ref("mdi-loading");
  const dialogMessage = ref("正在处理您的请求...");

  // 用户答案存储
  const answers = reactive({});

  // 加载状态
  const loading = ref(true);

  const errorMessage = ref("");

  // 提交状态
  const isSubmitting = ref(false);

  const isAnswered = ref(false);

  const questions = reactive([]);
  const title = ref("调查问卷");

  const requiredMessage = "信息不能为空";
  function required(v) {
    return !!v || requiredMessage;
  }
  // 身高校验规则，单位：厘米，范围 50 - 250
  function validateHeight(v) {
    const height = parseFloat(v);
    if (isNaN(height)) {
      return "请输入有效的身高数值";
    }
    if (height < 100 || height > 250) {
      return "身高应在 100 - 250 厘米之间";
    }
    return true;
  }

  // 体重校验规则，单位：千克，范围 10 - 300
  function validateWeight(v) {
    const weight = parseFloat(v);
    if (isNaN(weight)) {
      return "请输入有效的体重数值";
    }
    if (weight < 30 || weight > 300) {
      return "体重应在 30 - 300 千克之间";
    }
    return true;
  }

  // 提交表单
  const submitForm = async () => {
    const valid = await formRef.value?.validate();
    if (!valid.valid) {
      nextTick(() => {
        const firstErrorField =
          formRef.value.$el.querySelector(".v-input--error");

        if (firstErrorField) {
          firstErrorField.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }
      });
    } else {
      isSubmitting.value = true;
      isModalOpen.value = true;
      dialogType.value = "info";
      dialogIcon.value = "mdi-loading";
      dialogMessage.value = "正在处理您的请求...";

      const payload = {
        answers: JSON.stringify(answers),
      };
      try {
        // 提交到服务器
        const response = await postAnswer(route.params.id, payload);
        dialogType.value = "success";
        dialogIcon.value = "mdi-check";
        dialogMessage.value = "提交成功";
        setTimeout(() => {
          router.go(0);
        }, 1000);
      } catch (error) {
        console.error("提交问卷失败：", error.message);
        dialogType.value = "error";
        dialogIcon.value = "mdi-alert-circle";
        dialogMessage.value =
          `提交问卷失败，请稍后再试！\n${error.message}` || "未知错误，请重试";
      } finally {
        isSubmitting.value = false;
      }
    }
  };

  const handleLogout = () => {
    authStore.logout();
    router.push({ name: "Login", query: { redirect: route.path } });
  };

  onMounted(async () => {
    loading.value = true;
    try {
      const response = await getQuestionnaire(route.params.id);

      questions.push(...response.questions);
      Object.assign(answers, JSON.parse(response.answers));
      isAnswered.value = response.answered;
      title.value = response.title;

      setInterval(() => {
        loading.value = false;
      }, 1000);
    } catch (error) {
      console.error("获取数据失败", error);
      loading.value = false;
      if (error.response && error.response.data.message) {
        errorMessage.value = error.response.data.message;
      } else {
        errorMessage.value = "获取数据异常";
      }
    }
  });

  // 根据选项数量计算每列宽度
  const getCols = (cols) => {
    if (!cols || cols <= 1) return 12; // 每行最多2个选项，占满12列
    return 12 / cols; // 每行最多6个选项，每列占4列
  };
</script>

<style scoped>
  .questionnaire {
    max-width: 800px;
    margin: 0 auto;
  }
</style>
